package com.envision.common.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 
 * <strong>Title : SimpleCORSFilter.java<br>
 * </strong> <strong>Description : 解决前后端跨域问题</strong><br>
 * <strong>Create on : 2017年12月19日<br>
 * <p>
 * @author karrychang<br>
 * @version <strong>1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人		修改日期		修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class SimpleCORSFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(SimpleCORSFilter.class);
	public void destroy() {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpServletRequest request=(HttpServletRequest) req;

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String [] allowDomain= {"http://localhost:3001","http://localhost","http://localhost:3000"};
		Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
		String originHeader=((HttpServletRequest) req).getHeader("Origin");
		if (allowedOrigins.contains(originHeader)){
			response.setHeader("Access-Control-Allow-Origin", originHeader);
		}else {
			response.setHeader("Access-Control-Allow-Origin", "*");
		}
		response.setHeader("P3P","CP=CAO PSA OUR"); //解决IE不能跨域设置cookie
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		response.setHeader("Access-Control-Allow-Credentials","true");
        chain.doFilter(request, response);  
    }

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
